/*
 *  soapUI, copyright (C) 2006 eviware.com 
 *
 *  soapUI is free software; you can redistribute it and/or modify it under the 
 *  terms of the GNU Lesser General Public License as published by the Free Software Foundation; 
 *  either version 2.1 of the License, or (at your option) any later version.
 *
 *  soapUI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without 
 *  even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
 *  See the GNU Lesser General Public License for more details at gnu.org.
 */

package at.ac.tuwien.infosys.dsg.daios.wsdl.parser.soapui;

import java.io.InputStream;
import java.util.logging.Logger;

import javax.wsdl.xml.WSDLLocator;

import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.XmlOptions;
import org.xml.sax.InputSource;

public abstract class WsdlLoader implements WSDLLocator
{
	private final String url;
	private String last;
	protected static final Logger log = Logger.getLogger("Daios");

	public WsdlLoader( String url )
	{
		this.url = url;
	}

	public InputSource getBaseInputSource()
	{
		try
		{
			log.fine( "Returning baseInputSource [" + url + "]" );
			return new InputSource( load( url ) );
		}
		catch (Exception e)
		{
			throw new RuntimeException( e.toString() );
		}
	}

	public abstract InputStream load( String url ) throws Exception;
	
	public XmlObject loadXmlObject( String url, XmlOptions options ) throws Exception
	{
		if( options == null )
		{
			return XmlObject.Factory.parse( load( url ), new XmlOptions().setLoadLineNumbers());
		}
		else
		{
			options.setLoadLineNumbers();
			return XmlObject.Factory.parse( load( url ), options );
		}
	}

	public String getBaseURI()
	{
		log.fine( "Returning baseURI [" + url + "]" );
		return url;
	}

	public InputSource getImportInputSource(String parent, String imp)
	{
		if( isAbsoluteUrl( imp ))
			last = imp;
		else
			last = Tools.joinRelativeUrl( parent, imp);
		
		try
		{
			return new InputSource( load( last ) );
		}
		catch (Exception e)
		{
			throw new RuntimeException( e.toString() );
		}
	}

	protected boolean isAbsoluteUrl(String tempImp)
	{
		tempImp = tempImp.toUpperCase();
		return tempImp.startsWith( "HTTP:" ) || tempImp.startsWith( "HTTPS:" ) || tempImp.startsWith( "FILE:" );
	}

	public String getLatestImportURI()
	{
		String result = last == null ? url : last;
		log.fine( "Returning latest import URI [" + result + "]" );
		return result;
	}

	public abstract boolean abort();

	public abstract boolean isAborted();

}